<template>
  <div class="app-container add-container">
    <el-steps :active="active" finish-status="success" style="margin-bottom: 50px">
      <el-step title="填写商品信息"></el-step>
      <el-step title="填写商品营销"></el-step>
      <el-step title="填写商品属性"></el-step>
      <el-step title="选择商品关联"></el-step>
    </el-steps>

    <el-form v-if="active===0" :ref="'form' + active" :model="form1" :rules="rules1" label-width="120px">
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader v-model="form1.productCategoryId" :options="productCategoryOptions" :props="{label:'name', value:'id'}"/>
      </el-form-item>
      <el-form-item label="商品名称：" prop="name">
        <el-input v-model="form1.name"></el-input>
      </el-form-item>
      <el-form-item label="副标题：" prop="subTitle">
        <el-input v-model="form1.subTitle"></el-input>
      </el-form-item>
      <el-form-item label="商品品牌：" prop="brandId">
        <el-select v-model="form1.brandId">
          <el-option v-for="item in brandList"
                     :key="item.id" :label="item.name" :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片：" prop="pic">
        <upload-image v-model="form1.pic"></upload-image>
      </el-form-item>
      <el-form-item label="商品介绍：" prop="desc">
        <el-input type="textarea" v-model="form1.desc" :autosize="{ minRows: 4, maxRows: 10}" maxlength="500" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="商品售价：" prop="price">
        <el-input type="number" :min="0" v-model.number="form1.price"></el-input>
      </el-form-item>
      <el-form-item label="计量单位：" prop="unit">
        <el-input v-model="form1.unit" maxlength="8" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="商品重量（克）" prop="weight">
        <el-input type="number" :min="0" v-model.number="form1.weight"></el-input>
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input type="number" :min="0" v-model.number="form1.sort"></el-input>
      </el-form-item>
    </el-form>

    <el-form v-if="active===1" :ref="'form' + active" :model="form2" :rules="rules2" label-width="110px">
      <el-form-item label="赠送积分：" prop="giftPoint">
        <el-input type="number" :min="0" v-model.number="form2.giftPoint"></el-input>
      </el-form-item>
      <el-form-item label="商品上架：">
        <el-switch v-model="form2.publishStatus"
                   :active-value="1" :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="商品推荐：">
        <span class="mr5" style="display: inline-block">新品</span>
        <el-switch v-model="form2.newStatus"
                   :active-value="1" :inactive-value="0"
        ></el-switch>
        <span class="ml20 mr5" style="display: inline-block">推荐</span>
        <el-switch v-model="form2.recommendStatus"
                   :active-value="1" :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="服务保证：">
        <el-checkbox-group v-model="form2.serviceIds">
          <el-checkbox label="1">无忧退货</el-checkbox>
          <el-checkbox label="2">快速退款</el-checkbox>
          <el-checkbox label="3">免费包邮</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="商品关键字：">
        <el-input type="textarea" v-model="form2.keywords" placeholder="请输入商品关键字（一行输入一个）"
                  :autosize="{ minRows: 4, maxRows: 10}"/>
      </el-form-item>
      <el-form-item label="选择优惠方式：">
        <el-radio-group v-model="form2.promotionType" size="small" class="mb10">
          <el-radio-button :label="0">无优惠</el-radio-button>
          <el-radio-button :label="1">特惠促销</el-radio-button>
          <el-radio-button :label="2">会员价格</el-radio-button>
          <el-radio-button :label="3">阶梯价格</el-radio-button>
          <el-radio-button :label="4">满减价格</el-radio-button>
        </el-radio-group>
        <div v-if="form2.promotionType === 1">
          <div>
            <span>开始时间：</span>
            <el-date-picker v-model="form2.promotionStartTime"
                            size="mini"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择开始时间"
            >
            </el-date-picker>
          </div>
          <div>
            <span>结束时间：</span>
            <el-date-picker v-model="form2.promotionEndTime"
                            size="mini"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择结束时间"
            >
            </el-date-picker>
          </div>
          <div>
            <span>促销价格：</span>
            <el-input size="mini" style="width: 220px" type="number" :min="0" v-model="form2.promotionPrice"></el-input>
          </div>
          <div>
            <span>限购数量：</span>
            <el-input size="mini" style="width: 220px" type="number" :min="0" v-model="form2.promotionPerLimit"></el-input>
          </div>
        </div>
        <div v-if="form2.promotionType === 2">
          <div>
            <span>黄金会员：</span>
            <el-input type="number" :min="0" v-model.number="memberPriceList[0].memberPrice" size="mini" style="width: 220px"></el-input>
          </div>
          <div>
            <span>白金会员：</span>
            <el-input type="number" :min="0" v-model.number="memberPriceList[1].memberPrice" size="mini" style="width: 220px"></el-input>
          </div>
          <div>
            <span>钻石会员：</span>
            <el-input type="number" :min="0" v-model.number="memberPriceList[2].memberPrice" size="mini" style="width: 220px"></el-input>
          </div>
        </div>
        <div v-if="form2.promotionType === 3">
          <el-table :data="ladderList" border>
            <el-table-column label="数量" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-input style="width: 120px" type="number" :min="0" v-model.number="scope.row.count"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="折扣" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-input style="width: 120px" type="number"
                          :min="0" :max="10"
                          :value="scope.row.discount"
                          @input="handleInputDiscount($event, scope.row)"
                          @change="handleComputedPrice(scope.row)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleDeleteLadderItem(scope.$index)">删除</el-button>
                <el-button size="mini" type="text" @click="handleAddLadderItem">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="form2.promotionType === 4">
          <el-table :data="fullReductionList" border>
            <el-table-column label="满" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-input style="width: 120px" :min="0" type="number" v-model.number="scope.row.fullPrice"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="立减" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-input style="width: 120px" :min="0" :max="scope.row.fullPrice"
                          type="number" :value="scope.row.reducePrice" @input="handleInputFullPrice($event,scope.row)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" :resizable="false">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleDeleteReductionItem(scope.$index)">删除</el-button>
                <el-button size="mini" type="text" @click="handleAddReductionItem">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>

    <el-form v-if="active===2" :ref="'form' + active" :model="form3" :rules="rules3" label-width="110px">
      <el-form-item label="属性类型：" prop="productAttributeCategoryId">
        <el-select v-model.number="form3.productAttributeCategoryId" @change="handleChange">
          <el-option v-for="item in ProductAttributeCategoryList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格：">
        <div class="attr-box mb20">
          <div v-for="spec in specList" :key="spec.id">
            <span style="font-size: 15px">{{ spec.name + '：' }}</span>
            <el-checkbox-group class="ml20" v-model="spec.value">
              <template v-if="spec.inputType === 0">
                <el-checkbox v-for="val in spec.inputList" :key="val" :label="val">
                  <span>{{ val }}</span>
                  <el-button size="mini" type="text" class="ml5" @click="handleDeleteSpecItem(spec, val)">删除</el-button>
                </el-checkbox>
              </template>
              <template v-if="spec.inputType === 1">
                <el-checkbox v-for="val in spec.inputList" :key="val" :label="val">
                  <span>{{ val }}</span>
                </el-checkbox>
              </template>
            </el-checkbox-group>
            <div v-if="spec.inputType === 0" class="ml20">
              <el-input v-model.trim="spec.addContent" clearable size="small" class="mr20" style="width: 150px"></el-input>
              <el-button size="small" @click="handleAddSpecItem(spec)">增加</el-button>
            </div>
          </div>
        </div>
        <el-table :data="skuData" border class="mb20" max-height="700">
          <el-table-column v-for="(th, index) in skuTableTh" :key="index" :label="th.title">
            <template slot-scope="scope">
              {{ scope.row['v'+th.id] }}
            </template>
          </el-table-column>
          <el-table-column label="销售价格" align="center">
            <template slot-scope="scope">
              <el-input type="number" :min="0" v-model.number="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" align="center">
            <template slot-scope="scope">
              <el-input type="number" :min="0" v-model.number="scope.row.stock"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="sku编码" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skuCode" maxlength="64"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDeleteSku(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="small" type="primary" @click="handleRefreshTable">刷新列表</el-button>
      </el-form-item>
      <el-form-item label="属性图片：">
        <el-table :data="skuPicData" border class="mb20" max-height="700">
          <el-table-column v-for="(th, index) in skuPicTh" :key="index" :label="th.title">
            <template slot-scope="scope">
              {{ scope.row['v'+th.id] }}
            </template>
          </el-table-column>
          <el-table-column label="上传" align="center">
            <template slot-scope="scope">
              <upload-image v-model="scope.row.pic"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="商品参数：">
        <div class="param-box">
          <div v-for="param in paramList" :key="param.id" class="param-item mb10">
            <span class="param-label">{{ param.name + "：" }}</span>
            <el-input v-if="param.inputType === 0" v-model="param.value"></el-input>
            <el-select v-else v-model="param.value">
              <el-option v-for="(item, index) in param.inputList" :key="index" :label="item" :value="item" />
            </el-select>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="商品相册：">
        <uploadImage v-model="form3.albumPics"/>
      </el-form-item>
      <el-form-item label="详细描述：" prop="detail">
        <editor v-model="form3.detail" :min-height="192"/>
      </el-form-item>
    </el-form>

    <el-form v-if="active===3" :ref="'form' + active" :model="form4" :rules="rules4" label-width="110px">
      <el-form-item label="关联专题：" prop="subjectIds">
        <el-select v-model="subjectCategoryId" class="mb20" @change="handleChange3">
          <el-option v-for="item in subjectCategoryList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-transfer
            v-model="form4.subjectIds"
            filterable
            :titles="['待选择', '已选择']"
            :format="{noChecked: '${total}',hasChecked: '${checked}/${total}'}"
            :data="subjectList"
            :props="{key: 'id', label:'title'}"
        >
          <span slot-scope="{ option }">{{ option.title }}</span>
        </el-transfer>
      </el-form-item>
    </el-form>

    <el-alert
        style="cursor: pointer"
        @click.native="handleRedirect('click')"
        v-if="active === 4"
        :title="`商品${ isEdit ? '修改' : '添加' }成功，即将跳转到商品列表页......`"
        type="success"
        show-icon
        :closable="false">
    </el-alert>

    <div class="footer">
      <el-button v-if="active===0" type="primary" @click="next">下一步，填写商品营销</el-button>

      <el-button v-if="active===1" @click="pre">上一步，填写商品信息</el-button>
      <el-button v-if="active===1" type="primary" @click="next">下一步，填写商品属性</el-button>

      <el-button v-if="active===2" @click="pre">上一步，填写商品营销</el-button>
      <el-button v-if="active===2" type="primary" @click="next">下一步，选择商品关联</el-button>

      <el-button v-if="active===3" @click="pre">上一步，填写商品属性</el-button>
      <el-button v-if="active===3" type="primary" @click="handleSubmit">完成，提交商品</el-button>
    </div>
  </div>
</template>

<script>
import { listProductCategory } from "@/api/pms/productCategory";
import { listProductAttributeCategory } from "@/api/pms/productAttributeCategory";
import { listProductAttribute} from "@/api/pms/productAttribute";
import { listSubjectCategory } from "@/api/cms/subjectCategory";
import { getSubject, listSubject } from "@/api/cms/subject";
import { listBrand } from "@/api/pms/brand";
import { treeFindPath, treeFind, unique, assignPropsValue } from "@/utils";
import UploadImage from '@/components/UploadImage';
import Editor from '@/components/Editor';
import { addProduct, getProduct, updateProduct } from "@/api/pms/product";

export default {
  components: { UploadImage, Editor },

  props: ['isEdit'],

  computed: {
    productId() {
      return this.$route.query.id ? this.$route.query.id : null;
    }
  },

  created() {
    if (this.isEdit) {
      this.initEdit();
    } else {
      this.initAdd();
    }
  },

  data() {
    return {
      active: 0,
      form1: {
        productCategoryId: null,
        name: null,
        subTitle: null,
        brandId: null,
        pic: null,
        desc: null,
        price: null,
        unit: null,
        weight: null,
        sort: null,
        brandName: null
      },
      rules1: {
        productCategoryId: [
          { required: true, message: "商品分类不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        subTitle: [
          { required: true, message: "副标题不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "商品品牌不能为空", trigger: "change" }
        ],
        price: [
          { required: true, message: "商品售价不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "计量单位不能为空", trigger: "blur" }
        ],
        weight: [
          { required: true, message: "商品重量不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      },
      form2: {
        giftPoint: null,
        publishStatus: null,
        newStatus: null,
        recommendStatus: null,
        serviceIds: [],
        keywords: null,
        promotionType: 0,
        promotionStartTime: null,
        promotionEndTime: null,
        promotionPrice: null,
        promotionPerLimit: null
      },
      rules2: {},
      form3: {
        productAttributeCategoryId: null,
        albumPics: null,
        detail: null
      },
      rules3: {},
      form4: {
        subjectIds: []
      },
      rules4: {},
      memberPriceList: [
        { memberLevel: 0, memberPrice: null },
        { memberLevel: 1, memberPrice: null },
        { memberLevel: 2, memberPrice: null }
      ],
      ladderList: [
        {
          count: 0,
          discount: 0,
          price: null
        }
      ],
      fullReductionList: [
        {
          fullPrice: 0,
          reducePrice: 0
        }
      ],
      productCategoryOptions: [],
      ProductAttributeCategoryList: [],
      brandList: [],
      specList: [],
      paramList: [],
      skuData: [],
      skuTableTh: [],
      skuPicTh: [],
      skuPicData: [],
      subjectCategoryId: null,
      subjectCategoryList: [],
      subjectList: [],
      timeOut: null
    };
  },

  methods: {
    init() {
      listProductCategory().then(response => {
        this.productCategoryOptions = this.handleTree(response.rows);
      });
      listBrand().then(response => {
        this.brandList = response.rows;
      });
      listProductAttributeCategory().then(response => {
        this.ProductAttributeCategoryList = response.rows;
      });
      listSubjectCategory().then(response => {
        this.subjectCategoryList = response.rows;
      });
    },
    initAdd() {
      this.init();
      if (this.form3.productAttributeCategoryId) {
        this.getProductSpecList(this.form3.productAttributeCategoryId);
      }
      if (this.subjectCategoryId) {
        this.getSubjectList(this.subjectCategoryId);
      }
    },
    initEdit() {
      this.init();
      getProduct(this.productId).then(response => {
        if (!response.data) {
          this.$router.push({
            path: '/404'
          })
          return;
        }
        assignPropsValue(this.form1, response.data.product);
        this.$set(this.form1, 'productCategoryId', treeFindPath(this.productCategoryOptions, item => item.id === this.form1.productCategoryId));
        assignPropsValue(this.form2, response.data.product);
        this.form2.serviceIds = this.form2.serviceIds ? this.form2.serviceIds.split(',') : [];
        assignPropsValue(this.form3, response.data.product);
        assignPropsValue(this.form4, response.data.product);
        initPriceList(response.data.product, response.data, this);
        initAttributeValueList(response.data.attributeValueList, this).then(() => {
          initProductSkuList(response.data.productSkuList, this);
        });

        this.form4.subjectIds = response.data.subjectIds ? response.data.subjectIds : [];

        if (this.form4.subjectIds.length) {
          getSubject(this.form4.subjectIds[0]).then(response => {
            this.subjectCategoryId = response.data.categoryId;
            listSubject({ categoryId: this.subjectCategoryId }).then(response => {
              this.subjectList = response.rows;
            });
          });
        }

        function initPriceList(product, data, _this) {
          if (product.promotionType === 2) {
            _this.memberPriceList = data.memberPriceList;
          } else if (product.promotionType === 3) {
            _this.ladderList = data.ladderList;
          } else if (product.promotionType === 4) {
            _this.fullReductionList = data.fullReductionList;
          }
        }

        function initAttributeValueList(attributeValueList, _this) {
          return new Promise(resolve => {
            if (_this.form3.productAttributeCategoryId) {
              _this.getProductSpecList(_this.form3.productAttributeCategoryId).then(() => {
                _this.specList.forEach(spec => {
                  attributeValueList.forEach(item => {
                    if (spec.id === item.productAttributeId) {
                      _this.$set(spec, 'value', item.value ? item.value.split(',') : []);
                    }
                  });
                });
                _this.paramList.forEach(param => {
                  attributeValueList.forEach(item => {
                    if (param.id === item.productAttributeId) {
                      _this.$set(param, 'value', item.value);
                    }
                  })
                });
                resolve();
              });
            }
          });
        }

        function initProductSkuList(productSkuList, _this) {
          _this.handleRefreshTable();
          productSkuList.forEach(sku => {
            const spData = JSON.parse(sku.spData);
            _this.skuData.forEach(item => {
              let findFlag = true;
              spData.forEach(sp => {
                const id = _this.skuTableTh.find(th => th.title === sp.key).id;
                if (sp.value !== item['v' + id]) {
                  findFlag = false;
                }
              });
              if (findFlag) {
                _this.$set(item, 'price', sku.price);
                _this.$set(item, 'stock', sku.stock);
                _this.$set(item, 'skuCode', sku.skuCode);
              }
            });
          });
          _this.skuPicData.forEach(item => {
            productSkuList.forEach(sku => {
              const spData = JSON.parse(sku.spData);
              let findFlag = true;
              spData.forEach(sp => {
                const th = _this.skuPicTh.find(th => th.title === sp.key);
                if (th && sp.value !== item['v' + th.id]) {
                  findFlag = false;
                }
              });
              if (findFlag) {
                _this.$set(item, 'pic', sku.pic);
              }
            });
          });
        }
      });
    },
    next() {
      this.$refs['form' + this.active].validate((valid) => {
        if (valid) {
          if (this.active === 0) {
            this.form1.productCategoryId = this.form1.productCategoryId.pop();
            this.form1.productCategoryName = treeFind(this.productCategoryOptions, item => {
              return item.id === this.form1.productCategoryId;
            }).name;
            this.form1.brandName = this.brandList.find(item => {
              return item.id === this.form1.brandId;
            }).name;
          }
          if (this.active === 1) {
            this.form2.serviceIds = this.form2.serviceIds.join(',');
            this.form2.keywords = this.form2.keywords ? unique(this.form2.keywords.split(/\s+/)).join(',') : '';
            if (this.form2.promotionType === 3) {
              this.ladderList = this.ladderList.filter(item => item.count && item.discount);
            } else if (this.form2.promotionType === 4) {
              this.fullReductionList = this.fullReductionList.filter(item => item.fullPrice && item.reducePrice);
            }
          }
          this.active++;
        }
      });
    },
    pre() {
      if (this.active === 1) {
        this.form1.productCategoryId = treeFindPath(this.productCategoryOptions, item => {
          return item.id === this.form1.productCategoryId;
        });
      }
      if (this.active === 2) {
        this.form2.serviceIds = this.form2.serviceIds.split(',');
        this.form2.keywords = this.form2.keywords ? this.form2.keywords.split(',').join('\n') : '';
        if (!this.ladderList.length) {
          this.ladderList = [{
            count: 0,
            discount: 0,
            price: null
          }];
        }
        if (!this.fullReductionList.length) {
          this.fullReductionList = [{
            fullPrice: 0,
            reducePrice: 0
          }];
        }
      }
      this.active--;
    },
    handleDeleteLadderItem(index) {
      if (this.ladderList.length === 1) {
        this.msgWarning('请至少保留一个');
      } else {
        this.ladderList.splice(index, 1);
      }
    },
    handleAddLadderItem() {
      this.ladderList.push({
        count: 0,
        discount: 0
      });
    },
    handleDeleteReductionItem(index) {
      if (this.fullReductionList.length === 1) {
        this.msgWarning('请至少保留一个');
      } else {
        this.fullReductionList.splice(index, 1);
      }
    },
    handleAddReductionItem() {
      this.fullReductionList.push({
        fullPrice: 0,
        reducePrice: 0
      });
    },
    handleChange(id) {
      this.getProductSpecList(id);
    },
    getProductSpecList(id) {
      return new Promise(resolve => {
        listProductAttribute({ productAttributeCategoryId: id }).then(response => {
          let specList = response.rows.filter(item => {
            return item.type === 0;
          });
          let paramList = response.rows.filter(item => {
            return item.type === 1;
          });
          specList.forEach(item => {
            item.inputList = item.inputList ? item.inputList.split(',') : [];
            item.value = [];
          });
          paramList.forEach(item => {
            item.inputList = item.inputList.split(',');
          });
          this.specList = specList;
          this.paramList = paramList;
          resolve();
        });
      });
    },
    handleChange3(id) {
      this.form4.subjectIds = [];
      this.getSubjectList(id);
    },
    getSubjectList(id) {
      listSubject({ categoryId: id }).then(response => {
        this.subjectList = response.rows;
      });
    },
    handleAddSpecItem(spec) {
      if (!spec.addContent) {
        this.msgWarning('请输入内容');
      } else {
        if (spec.inputList.find(item => item === spec.addContent)) {
          this.msgWarning('属性值不能重复');
        } else {
          spec.inputList.push(spec.addContent);
        }
      }
      spec.addContent = '';
    },
    handleDeleteSpecItem(spec, val) {
      spec.inputList = spec.inputList.filter(item => item !== val);
      spec.value = spec.value.filter(item => item !== val);
    },
    handleDeleteSku(index) {
      this.skuData.splice(index, 1);
    },
    handleInputDiscount(val, row) {
      val = val && parseFloat(val);
      if (val >= 10) {
        row.discount = 10;
      } else {
        row.discount = val;
      }
    },
    handleComputedPrice(row) {
      if (row.count && row.discount) {
        row.price = this.form1.price * row.discount * 0.1;
      }
    },
    handleInputFullPrice(val, row) {
      val = val && parseFloat(val);
      if (val <= row.fullPrice) {
        row.reducePrice = val;
      }
    },
    handleRefreshTable() {
      let valueArray = [];
      let picValueArray = [];
      this.skuTableTh = [];
      this.skuPicTh = [];
      this.specList.forEach((item, index) => {
        if (item.value.length) {
          valueArray.push({ id: item.id, value: item.value });
          this.skuTableTh.push({ id: item.id, title: item.name });
          if (item.filterType === 1) {
            this.skuPicTh.push({ id: item.id, title: item.name });
            picValueArray.push({ id: item.id, value: item.value });
          }
        }
      });
      this.skuData = [];
      this.skuPicData = [];
      if (valueArray.length) {
        resolveValueArray(valueArray, this.skuData);
      }
      if (picValueArray.length) {
        resolveValueArray(picValueArray, this.skuPicData);
      }

      function resolveValueArray(array, data, i = 0, t = {}) {
        const id = array[i].id;
        array[i].value.forEach((v, index) => {
          t['v' + id] = v;
          if (i === array.length - 1) {
            data.push(JSON.parse(JSON.stringify(t)));
            return;
          }
          resolveValueArray(array, data, i + 1, t);
        });
      };
    },
    handleSubmit() {
      var submitData = {
        product: {
          ...this.form1,
          ...this.form2,
          ...this.form3,
        },
        memberPriceList: this.memberPriceList,
        ladderList: this.ladderList,
        fullReductionList: this.fullReductionList,
        subjectIds: this.form4.subjectIds
      };
      let attributeValueList = [];
      resolveAttributeValueList(attributeValueList, this.specList, this.paramList);
      submitData.attributeValueList = attributeValueList;
      let productSkuList = [];
      resolveProductSkuList(productSkuList, this.skuData, this.skuPicData, this.skuTableTh, this.skuPicTh);
      submitData.productSkuList = productSkuList;

      console.log('product', JSON.stringify(submitData));

      if (!this.isEdit) {
        addProduct(submitData).then(response => {
          this.msgSuccess('商品添加成功');
          this.active++;
          this.timeOut = setTimeout(() => {
            this.handleRedirect();
          }, 3000);
        });
      } else {
        submitData.product.id = this.productId;
        updateProduct(submitData).then(response => {
          this.msgSuccess('商品修改成功');
          this.active++;
          this.timeOut = setTimeout(() => {
            this.handleRedirect();
          }, 3000);
        });
      }

      function resolveAttributeValueList(target, specList, paramList) {
        const m1 = specList.map(item => {
          return {
            productAttributeId: item.id,
            value: item.value.join(',')
          };
        });
        const m2 = paramList.map(item => {
          return {
            productAttributeId: item.id,
            value: item.value
          };
        });
        target.push(...m1);
        target.push(...m2);
      }

      function resolveProductSkuList(target, skuData, skuPicData, skuTableTh, skuPicTh) {
        skuData.forEach(d => {
          skuPicData.forEach(p => {
            let findFlag = true;
            skuPicTh.forEach(pt => {
              if (p['v' + pt.id] !== d['v' + pt.id]) {
                findFlag = false;
              }
            });
            if (findFlag) {
              d.pic = p.pic;
            }
          });
        });
        const m = skuData.map(item => {
          let spData = [];
          skuTableTh.forEach(th => {
            spData.push({
              key: th.title,
              value: item['v' + th.id]
            });
          });
          return {
            ...item,
            spData: JSON.stringify(spData)
          };
        });
        target.push(...m);
      };
    },
    handleRedirect(click) {
      if (click) {
        clearTimeout(this.timeOut);
      }
      const fullPath = this.$route.fullPath;
      Object.assign(this.$data, this.$options.data());
      this.resetForm("form0");
      this.$store.dispatch('tagsView/delView', this.$store.getters.visitedViews.find(item => item.fullPath === fullPath)).then(() => {
        this.$router.replace({
          path: '/redirect' + '/pms/product'
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.add-container {
  margin-top: 20px;
  margin-left: 10%;
  width: 70%;
  border: 1px solid #EBEEF5;
  padding: 50px 70px;
}

.footer {
  text-align: center;
  margin-top: 12px;
}

.attr-box {
  background: #F8F9FC;
  border: 1px solid #EBEEF5;
  border-radius: 3px;
  padding: 10px 20px;
  min-height: 30px;
}

.param-box {
  background: #F8F9FC;
  padding: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 3px;
  .param-item {
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
  }
  .param-label {
    text-align: right;
    width: 72px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-right: 10px;
  }
}
</style>